// pages/student/xiaoxi/xiaoxi.js
Page({
  data: {
    messageList: [],
    unreadCount: 0,
    isLoading: true
  },

  onLoad: function() {
    this.loadMessages();
  },

  onShow: function() {
    // 每次页面显示时刷新消息列表
    this.loadMessages();
  },

  onPullDownRefresh: function() {
    this.loadMessages().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载消息列表
  loadMessages: function() {
    this.setData({ isLoading: true });
    
    // 获取应用实例以获取服务器地址
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const userId = wx.getStorageSync('userId') || '2021001'; // 从本地存储获取用户ID
    
    // 使用微信内置图标
    const messageTypeIcons = {
      system: 'notification',
      personal: 'chat',
      leave: 'info',
      exam: 'warn',
      attendance: 'success'
    };
    
    return new Promise((resolve) => {
      wx.request({
        url: `${serverUrl}/api/messages/student/messages?userId=${userId}`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            // 格式化消息数据
            const messages = res.data.messages || [];
            const formattedMessages = messages.map(msg => {
              // 将数据库日期格式化为更友好的显示格式
              const sendTime = new Date(msg.sendTime);
              const formattedTime = `${sendTime.getFullYear()}-${String(sendTime.getMonth() + 1).padStart(2, '0')}-${String(sendTime.getDate()).padStart(2, '0')} ${String(sendTime.getHours()).padStart(2, '0')}:${String(sendTime.getMinutes()).padStart(2, '0')}`;
              
              return {
                ...msg,
                createTime: formattedTime, // 前端使用createTime显示
                iconType: messageTypeIcons[msg.type] || 'info' // 使用微信内置图标类型
              };
            });
            
            this.setData({
              messageList: formattedMessages,
              unreadCount: res.data.unreadCount || 0,
              isLoading: false
            });
          } else {
            this.setData({ isLoading: false });
            wx.showToast({
              title: '获取消息失败',
              icon: 'none'
            });
          }
          resolve();
        },
        fail: (err) => {
          console.error('获取消息失败:', err);
          this.setData({ isLoading: false });
          wx.showToast({
            title: '网络连接失败',
            icon: 'none'
          });
          resolve();
        }
      });
    });
  },

  // 查看消息详情
  viewMessageDetail: function(e) {
    const messageId = e.currentTarget.dataset.id;
    console.log('点击消息ID:', messageId);
    
    if (!messageId) {
      console.error('消息ID为空');
      return;
    }
    
    // 获取消息对象
    const message = this.data.messageList.find(item => item.id === messageId);
    console.log('找到的消息对象:', message);
    
    if (!message) {
      console.error('找不到对应的消息对象');
      wx.showToast({
        title: '消息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 标记为已读
    this.markAsRead(messageId);
    
    try {
      // 将消息列表保存到本地存储，供详情页使用
      wx.setStorageSync('messageList', this.data.messageList);
      
      // 检查消息标题或内容是否包含请假关键词
      const isLeaveRelated = 
        (message.title && (message.title.includes('请假') || message.title.includes('批准'))) || 
        (message.content && message.content.includes('请假'));
      
      // 尝试从消息内容中提取请假ID
      let leaveId = null;
      if (isLeaveRelated) {
        // 尝试匹配格式如"请假ID:123"或"leaveId:123"的内容
        const leaveIdMatch = message.content.match(/[请假ID|leaveId]:(\d+)/i);
        if (leaveIdMatch) {
          leaveId = leaveIdMatch[1];
        }
      }
      
      if (isLeaveRelated) {
        if (leaveId) {
          console.log('跳转到请假详情页, ID:', leaveId);
          // 如果是请假相关消息且找到了请假ID，跳转到请假详情页
          wx.navigateTo({
            url: `/pages/student/qingjiaxiangqing/qingjiaxiangqing?id=${leaveId}`,
            fail: (err) => {
              console.error('跳转到请假详情页失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        } else {
          console.log('跳转到请假记录页面');
          wx.navigateTo({
            url: '/pages/student/qingjiajilu/qingjiajilu',
            fail: (err) => {
              console.error('跳转到请假记录页面失败:', err);
              wx.showToast({
                title: '页面跳转失败',
                icon: 'none'
              });
            }
          });
        }
      } else {
        console.log('跳转到消息详情页, ID:', messageId);
        // 其他类型消息跳转到消息详情页
        wx.navigateTo({
          url: `/pages/student/xiaoxi/detail/detail?id=${messageId}`,
          fail: (err) => {
            console.error('跳转到消息详情页失败:', err);
            wx.showToast({
              title: '页面跳转失败',
              icon: 'none'
            });
          }
        });
      }
    } catch (error) {
      console.error('跳转过程中发生错误:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 标记消息为已读
  markAsRead: function(messageId) {
    const messageList = this.data.messageList;
    const index = messageList.findIndex(item => item.id === messageId);
    
    if (index !== -1 && !messageList[index].isRead) {
      messageList[index].isRead = true;
      
      this.setData({
        messageList: messageList,
        unreadCount: this.data.unreadCount - 1
      });
      
      // 获取应用实例以获取服务器地址
      const app = getApp();
      const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
      
      // 发送已读请求
      wx.request({
        url: `${serverUrl}/api/messages/student/messages/${messageId}/read`,
        method: 'PUT',
        success: (res) => {
          console.log('标记消息已读成功', res);
        },
        fail: (err) => {
          console.error('标记消息已读失败', err);
        }
      });
    }
  },

  // 标记所有为已读
  markAllAsRead: function() {
    if (this.data.unreadCount === 0) {
      wx.showToast({
        title: '没有未读消息',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '提示',
      content: '确定将所有消息标记为已读吗？',
      success: (res) => {
        if (res.confirm) {
          const messageList = this.data.messageList.map(item => {
            return {...item, isRead: true};
          });
          
          this.setData({
            messageList: messageList,
            unreadCount: 0
          });
          
          // 获取应用实例以获取服务器地址
          const app = getApp();
          const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
          const userId = wx.getStorageSync('userId') || '2021001';
          
          // 发送全部已读请求
          wx.request({
            url: `${serverUrl}/api/messages/student/messages/read-all?userId=${userId}`,
            method: 'PUT',
            success: () => {
              wx.showToast({
                title: '已全部标为已读',
                icon: 'success'
              });
            },
            fail: () => {
              wx.showToast({
                title: '操作失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 跳转到AI聊天页面
  navigateToAIChat: function() {
    wx.navigateTo({
      url: '/pages/ai-chat/ai-chat'
    });
  }
});